package com.ruoyi.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.jcraft.jsch.Session;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.ExecuteLog;
import com.ruoyi.system.domain.THost;
import com.ruoyi.system.domain.TScript;
import com.ruoyi.system.mapper.ExecuteLogMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.THostMapper;
import com.ruoyi.system.mapper.TScriptMapper;
import com.ruoyi.system.pool.Executor;
import com.ruoyi.system.pool.ShellExecutor;
import com.ruoyi.system.pool.SshClientPool;
import com.ruoyi.system.service.TScriptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 脚本(TScript)表服务实现类
 *
 * @author stone
 * @since 2022-04-15 17:12:12
 */
@Service("tScriptService")
public class TScriptServiceImpl implements TScriptService {
    @Autowired
    private TScriptMapper tScriptMapper;


    @Autowired
    private ExecuteLogMapper executeLogMapper;

    @Autowired
    private THostMapper tHostMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SshClientPool sshClientPool;


    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public TScript queryById(Integer id) {
        return this.tScriptMapper.queryById(id);
    }

    /**
     * 分页查询
     *
     * @param tScript 筛选条件
     * @return 查询结果
     */
    @Override
    public List<TScript> page(TScript tScript) {

        List<TScript> tScripts = this.tScriptMapper.queryAll(tScript);
        tScripts.forEach(e -> {
            e.setCreatorName(sysUserMapper.selectUserById(e.getCreator().longValue()).getUserName());
            if (e.getModifier() != null)
                e.setModifierName(sysUserMapper.selectUserById(e.getModifier().longValue()).getUserName());
        });
        return tScripts;

    }

    /**
     * 新增数据
     *
     * @param tScript 实例对象
     * @return 实例对象
     */
    @Override
    public int insert(TScript tScript) {
        tScript.setCreateTime(new Date());
        Long userId = SecurityUtils.getUserId();
        tScript.setCreator(userId.intValue());
        return this.tScriptMapper.insert(tScript);

    }

    /**
     * 修改数据
     *
     * @param tScript 实例对象
     * @return 实例对象
     */
    @Override
    public int update(TScript tScript) {
        Long userId = SecurityUtils.getUserId();
        tScript.setModifier(userId.intValue());
        tScript.setModifyTime(new Date());
        return this.tScriptMapper.update(tScript);
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public int deleteById(Integer id) {
        return this.tScriptMapper.deleteById(id);
    }


    @Override
    public int deleteByIds(String ids) {
        if (StrUtil.isBlank(ids)) {
            return 0;
        }
        Arrays.stream(ids.split(",")).map(Integer::parseInt).forEach(e -> this.tScriptMapper.deleteById(e));
        return 1;
    }


    @Override
    public int runScript(Integer scriptId, String hostIds) {

        if (StrUtil.isBlank(hostIds)) {
            return 0;
        }

        TScript tScript = tScriptMapper.queryById(scriptId);


        Arrays.stream(hostIds.split(",")).map(Integer::parseInt).forEach(e -> {
            //tScriptMapper.deleteById(e);
            THost tHost = tHostMapper.queryById(e);
            //Integer integer = SshClientPool.runScript(tHost, tScript.getContent());
            ExecuteLog log = new ExecuteLog();
            try {
                Session session = sshClientPool.borrowObject(tHost.getHostname());
                Executor<String> executor = new ShellExecutor(session);
                String result = executor.execute(tScript.getContent());
                log.setContent(result);
                log.setFlag(1);
            } catch (Exception ex) {
                ex.printStackTrace();
                log.setContent(ex.getMessage());
                log.setFlag(0);
            }

            //log.setContent(tHost.getRemark());
            log.setCreateTime(new Date());

            //log.setFlag(integer);
            log.setHostId(e);
            log.setScriptId(scriptId);
            executeLogMapper.insert(log);

        });
        return 1;
    }


}
